package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.IhotArticleService;
import com.heima.behavior.dto.ArticleStreamMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: itheima
 * @create: 2022-05-25 12:03
 */
@Service
public class hotArticleServiceImpl implements IhotArticleService {

    @Autowired
    private IApArticleService apArticleService;
    ;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询最近五天发布文章对每篇文章得分进行计算；将文章数据缓存到redis中（zset数据结构）
     */
    @Override
    public void compute() {
        //1.查询最近五天发布文章对每篇文章得分进行计算（条件：上架，未删除）
        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        //1.1 上架状态
        queryWrapper.eq(ApArticle::getIsDown, false);
        //1.2 删除状态
        queryWrapper.eq(ApArticle::getIsDelete, false);

        //1.3 增加日期区间
        Date toDate = getFromAndToDate(0);
        Date fromDate = getFromAndToDate(-30);
        queryWrapper.between(ApArticle::getPublishTime, fromDate, toDate);
        List<ApArticle> list = apArticleService.list(queryWrapper);
        //2.遍历文章集合，计算分值
        if (!CollectionUtils.isEmpty(list)) {
            //2.1 声明redis热点数据Key前缀+数字    首页中数据：key+0：  其他频道：key+频道id
            String redisKeyPrefix = "leadnews:article:hot:page:";
            for (ApArticle article : list) {
                //2.2 计算文章得分
                int score = computeScore(article);
                //2.3 将文章缓存到redis中
                ApArticle cache = new ApArticle();
                cache.setId(article.getId());
                cache.setTitle(article.getTitle());
                cache.setImages(article.getImages());
                cache.setAuthorId(article.getAuthorId());
                cache.setAuthorName(article.getAuthorName());
                cache.setLayout(article.getLayout());
                cache.setStaticUrl(article.getStaticUrl());

                String value = JSON.toJSONString(cache);
                //2.3.1 将数据存入首页key
                String indexKey = redisKeyPrefix + "0";
                redisTemplate.opsForZSet().add(indexKey, value, score);

                //2.3.2 将数据存入其他频道key
                String chananelKey = redisKeyPrefix + article.getChannelId();
                redisTemplate.opsForZSet().add(chananelKey, value, score);

                //2.4 设置过期时间
                redisTemplate.expire(indexKey, 1, TimeUnit.DAYS);
                redisTemplate.expire(chananelKey, 1, TimeUnit.DAYS);
            }
        }
    }


    /**
     * 获取指定天数日期 正数：未来时间  负数：以前时间
     *
     * @param datecount
     * @return
     */
    public static Date getFromAndToDate(Integer datecount) {
        //创建日期对象
        Calendar calendar = Calendar.getInstance();
        //设置日期
        calendar.add(Calendar.DATE, datecount);
        //设置时分秒
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    /**
     * 为入参的文章计算分值
     *
     * @param article
     * @return
     */
    private int computeScore(ApArticle article) {
        int score = 0;
        // 阅读 +1  点赞 +3  评论 +5  收藏 +8
        if (article.getViews() != null) {
            score += article.getViews() * 1;
        }
        if (article.getLikes() != null) {
            score += article.getLikes() * 3;
        }
        if (article.getComment() != null) {
            score += article.getComment() * 5;
        }
        if (article.getCollection() != null) {
            score += article.getCollection() * 8;
        }
        return score;
    }


    /**
     * 根据实时计算热点文章行为结果：1.更新分布式缓存Redis中首页热点数据  2.更新数据库中文章的行为数量
     *
     * @param articleStreamMessage 聚合到某个文章各种行为操作次数值
     */
    @Override
    public void updateArticleCacheAndInfo(ArticleStreamMessage articleStreamMessage) {
        //1.根据文章ID 查询文章记录
        ApArticle article = apArticleService.getById(articleStreamMessage.getArticleId());

        //2.构建Redis缓存文章对象;将数据缓存到redis
        ApArticle cache = new ApArticle();
        cache.setId(article.getId());
        cache.setTitle(article.getTitle());
        cache.setImages(article.getImages());
        cache.setAuthorId(article.getAuthorId());
        cache.setAuthorName(article.getAuthorName());
        cache.setLayout(article.getLayout());
        cache.setStaticUrl(article.getStaticUrl());
        String value = JSON.toJSONString(cache);
        //2.1 计算文章增量得分
        int addScore = computeScore(articleStreamMessage);

        //2.2 判断redis中是否包含该文章
        String redisKeyPrefix = "leadnews:article:hot:page:";
        String redisIndexKey = redisKeyPrefix + "0";
        String redisChannelKey = redisKeyPrefix + article.getChannelId();
        Double indexScore = redisTemplate.opsForZSet().score(redisIndexKey, value);
        //2.2.1 如果缓存中存在该文章：在现有缓存数据分之累加增量得分
        if (indexScore != null) {
            redisTemplate.opsForZSet().incrementScore(redisIndexKey, value, addScore);
            redisTemplate.opsForZSet().incrementScore(redisChannelKey, value, addScore);
        } else {
            //2.2.2 反之缓存中没有数据：根据数据库中现有文章操作得分跟增量得分累加 存入redis
            int historyScore = computeScore(article);
            redisTemplate.opsForZSet().add(redisIndexKey, value, addScore+historyScore);
            redisTemplate.opsForZSet().add(redisChannelKey, value, addScore+historyScore);
        }
        //3.更新数据库中文章的行为数量
        LambdaUpdateWrapper<ApArticle> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ApArticle::getId, article.getId());
        updateWrapper.setSql("views = views +" + articleStreamMessage.getView());
        updateWrapper.setSql("likes = likes +" + articleStreamMessage.getLike());
        updateWrapper.setSql("comment = comment +" + articleStreamMessage.getComment());
        updateWrapper.setSql("collection = collection +" + articleStreamMessage.getCollect());
        apArticleService.update(updateWrapper);
    }


    /**
     * 计算当日的增量分数  当日的操作整体权重*3
     *
     * @param message
     * @return
     */
    private int computeScore(ArticleStreamMessage message) {
        int score = 0;
        score += message.getView() * 1 * 3;
        score += message.getLike() * 3 * 3;
        score += message.getComment() * 5 * 3;
        score += message.getCollect() * 8 * 3;
        return score;
    }
}
